package com.itheima.web.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.domain.db.Questions;
import com.itheima.domain.db.QuestionsOption;
import com.itheima.domain.vo.PageResult;
import com.itheima.domain.vo.SoulTestQuestionVo;
import com.itheima.dubbo.api.QuestionsApi;
import com.itheima.dubbo.api.QuestionsOptionApi;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * desc
 *
 * @author mu
 * @date 2021/3/2 18:36
 */
@Service
public class SoulTestService {

    @Reference
    private QuestionsApi questionsApi;
    @Reference
    private QuestionsOptionApi questionsOptionApi;

    public ResponseEntity getQuestionAndOption(String qid) {
        // 获取测试题信息
        Questions question = questionsApi.findById(qid);
        // 获取测试题对应选项信息
        List<QuestionsOption> options = questionsOptionApi.findListByQid(Long.parseLong(qid));
        // 封装并返回数据
        SoulTestQuestionVo result = new SoulTestQuestionVo();
        result.setId(question.getId());
        result.setCid(question.getCid());
        result.setQuestion(question.getQuestion());
        result.setOptions(options);
        return ResponseEntity.ok(result);
    }

    public ResponseEntity<String> insertOrUpdateQuestion(SoulTestQuestionVo data) {
        // 判断测试题是否为已存在,若数据内题目id存在,则该题目已存在
        Long id = data.getId();
        if (id != null) {
            // 更新
            Questions questions = new Questions();
            questions.setId(data.getId());
            questions.setCid(data.getCid());
            questions.setQuestion(data.getQuestion());
            questionsApi.updataById(questions);
            questionsOptionApi.updateListById(data.getOptions());
        } else {
            // 新增
            questionsApi.insertQuestionAndOption(data);
        }
        return ResponseEntity.ok("ok");
    }


    /**
     * 分页查询试题列表
     * @param page 页码
     * @param pagesize 查询几条
     * @param id 试题id
     * @return
     */
    public ResponseEntity findList(int page, int pagesize, Integer id) {
        IPage<Questions> iPage = questionsApi.findList(page, pagesize, id);
        PageResult<Questions> pageResult = new PageResult<>();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        pageResult.setPages((int) iPage.getPages());
        pageResult.setCounts((int) iPage.getTotal());
        pageResult.setItems(iPage.getRecords());
        return ResponseEntity.ok(pageResult);
    }
}
